package com.zhiyume.api.controller;

import com.zhiyume.api.util.ApiConstants;
import com.zhiyume.api.util.Sign;
import com.zhiyume.api.util.WXPublicUtils;
import com.zhiyume.dao.api.TActivityMapper;
import com.zhiyume.dao.api.TInformationMapper;
import com.zhiyume.dao.entity.*;
import com.zhiyume.exception.AesException;
import com.zhiyume.exception.AppException;
import com.zhiyume.oss.OssUpload;
import com.zhiyume.page.PageReq;
import com.zhiyume.page.Pager;
import com.zhiyume.service.*;
import com.zhiyume.service.common.ConstantEnum;
import com.zhiyume.service.util.DateUtil;
import com.zhiyume.service.util.JsonUtil;
import com.zhiyume.service.util.StringUtil;
import com.zhiyume.util.TypeConstants;
import com.zhiyume.vo.PersonReqVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.text.ParseException;
import java.util.*;

import static com.zhiyume.util.TypeConstants.IMAGE_BIG_FLOOR;
import static com.zhiyume.util.TypeConstants.IMAGE_FLOOR;
import static com.zhiyume.util.TypeConstants.StyleConstants.*;

/**
 * Created by wang on 17/10/30.
 */
@Controller
@RequestMapping("/api/detail")
@Api(tags = "各类详情接口")
public class AnyDetailController extends AppBaseAction{
    private static final String MODULE = AnyDetailController.class.getName();
    private static final Logger logger = LoggerFactory.getLogger(AnyDetailController.class);
    private static final String URL = "page/h5";

    @Autowired
    private InformationService informationService;
    @Autowired
    private TActivityService activityService;
    @Autowired
    private TPersonService tPersonService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private IDramaService iDramaService;


    @Autowired
    TInformationMapper tInformationMapper;
    @Autowired
    private TActivityMapper tActivityMapper;


    private String successType = ConstantEnum.CONSTANT_SUCCESS.getErrType();
    private String successMsg = ConstantEnum.CONSTANT_SUCCESS.getErrMsg();



    @ResponseBody
    @RequestMapping(value = "/getweixinconfig", method = RequestMethod.POST)
    @ApiOperation(value = "微信分享")
    public Map getWeixinConfig(@RequestParam("url") String url){


        String jsapi_ticket = redisService.getWXTICKETData();

        logger.error("jsapi_ticket:【"+jsapi_ticket+"】");
        if(StringUtil.isBlank(jsapi_ticket)){
            String access_tocken = redisService.getWXTOKENData();

            logger.error("access_tocken1:【"+access_tocken+"】");

            if(StringUtil.isBlank(access_tocken)){
                JSONObject tokenInfo = WXPublicUtils.getToken();
                if(tokenInfo!=null){
                    access_tocken = tokenInfo.getString("access_token");
                    logger.error("access_tocken2:【"+access_tocken+"】");
                    String expires_in = tokenInfo.getString("expires_in");
                    redisService.setWXTOKENData(access_tocken,Integer.valueOf(expires_in)/2);
                }
            }

            JSONObject JSAPI = WXPublicUtils.getJsApiTicket(access_tocken);
            if(JSAPI!=null){
                jsapi_ticket= JSAPI.getString("ticket");
                logger.error("jsapi_ticket2:【"+jsapi_ticket+"】");
                String expires_in = JSAPI.getString("expires_in");
                redisService.setWXTICKETData(jsapi_ticket,Integer.valueOf(expires_in)/2);
            }
        }

        return Sign.sign(jsapi_ticket,url);
    }

    @RequestMapping(value = "/information/{id}",method = RequestMethod.GET)
    @ApiIgnore
    public ModelAndView information(@PathVariable("id") Long id,
                                    HttpServletRequest request,
                                    @RequestHeader(value=TypeConstants.TOKEN_API_KEY,defaultValue = "")
                                            String token) throws AppException,ParseException{
        ModelAndView mv = new ModelAndView();

        redisService.userRead(token);

        if(null!=id&&id>-1){
            TInformationWithBLOBs t = informationService.findInfoWithBlobsById(id);
            //处理日期
            if(StringUtil.isNotBlank(t.getPublishTime())){
                Date date = DateUtils.parseDate(t.getPublishTime(),"yyyy-MM-dd HH:mm:ss");
                mv.addObject("publishTime",DateUtil.date2String(date,"yyyy-MM-dd HH:mm"));
            }
            List<TInformationWithBLOBs> tInformationList = informationService.getIntroInformationList(t.getId(),5);
            mv.addObject("tInformation",t);
            mv.addObject("list",tInformationList);

            mv.addObject("pv",redisService.informationHaveRead(id));
            mv.setViewName("page/h5/information_detail");
        }else{
            mv.setViewName("page/mobile/demo");
        }



        //是否展示评论
        if(ifLogin(token)){
            mv.addObject("ifLogin","1");

//            List<TComment> comments = commentService.findCommentByInformationId(id);
//            mv.addObject("comments",comments);
        }


        redisService.informationRead(id);

        mv.addObject("url",request.getRequestURL());

        return mv;
    }

    @RequestMapping(value = "/activity/{id}",method = RequestMethod.GET)
    @ApiIgnore
    public ModelAndView activity(@PathVariable("id") Long id,
                                    @RequestHeader(value=TypeConstants.TOKEN_API_KEY,defaultValue = "")
                                            String token) throws AppException,ParseException{
        ModelAndView mv = new ModelAndView();

        redisService.userRead(token);

        if(null!=id&&id>-1){
            TActivity t = activityService.findActivityById(id);

            if(t==null){
                mv.setViewName("page/h5/demo");
                return mv;
            }
            //处理日期
            if(StringUtil.isNotBlank(t.getPublishTime())){
                Date date = DateUtils.parseDate(t.getPublishTime(),"yyyy-MM-dd HH:mm:ss");
                mv.addObject("publishTime",DateUtil.date2String(date,"yyyy-MM-dd HH:mm"));
            }
            if(StringUtil.isNotBlank(t.getDeadlineTime())){
                Date date = DateUtils.parseDate(t.getDeadlineTime(),"yyyy-MM-dd HH:mm:ss");
                mv.addObject("deadlineTime",DateUtil.date2String(date,"yyyy-MM-dd HH:mm"));
            }


            mv.addObject("tActivity",t);
            mv.addObject("pv",(redisService.activityHaveRead(id) + (long)t.getShareNum()));

            List<TActivity> tActivities = activityService.getActivityOtherList(t.getId(),5);
            mv.addObject("list",tActivities);

            mv.setViewName("page/h5/activity_detail");
        }else{
            mv.setViewName("page/h5/demo");
        }

        redisService.activityRead(id);

        return mv;
    }



    @RequestMapping(value = "/actor/{id}",method = RequestMethod.GET)
    @ApiIgnore
    public String actor(@PathVariable("id") Long id,Model model,
                        HttpServletRequest request) throws AppException{
        String url = URL;
        if(null!=id&&id>-1){
            TPersonWithBLOBs t = tPersonService.findPersonById(id);
            PersonReqVO reqVO = new PersonReqVO();
            reqVO.setId(id);
            List<Map> repWorks = tPersonService.getRepWorks(reqVO);
            model.addAttribute("actor",t);

            List<TDrama> dramas = new ArrayList<>();
            for(Map repWork:repWorks){
                dramas.add(iDramaService.findDramaById((Long)repWork.get("dId")));
            }
            model.addAttribute("dramas",dramas);

            //判断浏览器类型
            String userAgent = request.getHeader("User-Agent");
            boolean ifIos = userAgent.toLowerCase().contains("ip");
            logger.info(userAgent.toLowerCase());

            model.addAttribute("ifIos",ifIos?"1":"2");

            return url+"/person_detail";
        }else{
            url = "page/mobile/demo";
        }
        return url;
    }


    @RequestMapping(value = "/drama/{id}",method = RequestMethod.GET)
    @ApiIgnore
    public ModelAndView drama(@PathVariable("id") Long id) throws AppException{
        String url = "";
        ModelAndView modelAndView = new ModelAndView();
        if(null!=id&&id>-1){
            TDrama drama = iDramaService.findDramaById(id);
            PersonReqVO reqVO = new PersonReqVO();
            reqVO.setId(id);
            List<TDramaPerson> dramaPeople = tPersonService.getDramaPerson(id);
            modelAndView.addObject("personList",dramaPeople);
            modelAndView.addObject("drama",drama);
            url+="page/h5/dramaDetail";
        }else{
            url = "page/mobile/demo";
        }
        modelAndView.setViewName(url);
        return modelAndView;
    }

    @RequestMapping(value = "/wxpublic/verify_wx_token", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "微信获取签名")
    public String verifyWXToken(HttpServletRequest request) throws AesException {
        String msgSignature = request.getParameter("signature");
        String msgTimestamp = request.getParameter("timestamp");
        String msgNonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        logger.error(MODULE,msgSignature);
        logger.error(MODULE,msgTimestamp);
        logger.error(MODULE,msgNonce);
        logger.error(MODULE,echostr);
        if (WXPublicUtils.verifyUrl(msgSignature, msgTimestamp, msgNonce)) {
            return echostr;
        }
        return null;
    }

    @ResponseBody
    @RequestMapping(value = "/pinfo", method = RequestMethod.GET)
    @ApiOperation(value = "咨询详情")
    public Map information(PageReq page) throws Exception{

        Pager p = getInfoDetailDataPager(page);
        return JsonUtil.returnResult(successType, successMsg,p);
    }

    @ResponseBody
    @RequestMapping(value = "/pactor", method = RequestMethod.GET)
    @ApiOperation(value = "演员详情")
    public Map actor(PageReq page) throws Exception{

        Pager p = getActorDetailDataPager(page);
        return JsonUtil.returnResult(successType, successMsg,p);
    }


    @ResponseBody
    @RequestMapping(value = "/pactivity", method = RequestMethod.GET)
    @ApiOperation(value = "活动详情")
    public Map activity(PageReq page) throws Exception{

        Pager p = getActivityDataPager(page);
        return JsonUtil.returnResult(successType, successMsg,p);
    }

    private Pager getInfoDetailDataPager(PageReq page) throws Exception{
        Pager p = new Pager();


        p.setTotalCount(1);


        TInformationCriteria t = new TInformationCriteria();
        TInformationCriteria.Criteria ct = t.createCriteria();

        ct.andIdEqualTo(page.getDataId());

        //翻页
        t.setLimitStart(0);
        t.setLimitEnd(page.getPageSize());

        List<TInformation> ts = tInformationMapper.selectByExample(t);


        List<Map> datas = new ArrayList<Map>();

        datas.addAll(getInfoRenderData(ts));

        p.setPageSize(page.getPageSize());

        p.setItems(datas);
        return p;
    }

    private Pager getActorDetailDataPager(PageReq page) throws Exception{
        Pager p = new Pager();


        p.setTotalCount(1);


        TPersonCriteria t = new TPersonCriteria();
        TPersonCriteria.Criteria ct = t.createCriteria();

        ct.andIdEqualTo(page.getDataId());

        //翻页
        t.setLimitStart(0);
        t.setLimitEnd(page.getPageSize());

        List<TPerson> ts = tPersonService.findActorById(page.getDataId());


        List<Map> datas = new ArrayList<Map>();

        datas.addAll(getActorRenderData(ts));

        p.setPageSize(page.getPageSize());

        p.setItems(datas);
        return p;
    }

    private Collection<? extends Map> getActorRenderData(List<TPerson> ts) {
        List<Map> datas = new ArrayList<Map>();

        //哨兵
        for(TPerson t:ts){
            Map temp = new HashMap();
            Map dataItem = new HashedMap();

            temp.put("name",t.getName());
            temp.put("img_url",t.getFaceurl());
            temp.put("gender",t.getGender());
            temp.put("career",t.getCareer());
            temp.put("id",t.getId().toString());
            temp.put("birth", t.getBirth());
            temp.put("height",t.getHeight());

            dataItem.put("item",temp);
            datas.add(dataItem);
        }

        return datas;

    }


    //普通栏目列表数据获取
    private Pager getActivityDataPager(PageReq page) throws Exception{
        Pager p = new Pager();


        p.setTotalCount(1);


        TActivityCriteria t = new TActivityCriteria();
        TActivityCriteria.Criteria ct = t.createCriteria();

        ct.andIdEqualTo(page.getDataId());

        //翻页
        t.setLimitStart(0);
        t.setLimitEnd(page.getPageSize());

        List<TActivity> ts = tActivityMapper.selectByExample(t);


        List<Map> datas = new ArrayList<Map>();

        datas.addAll(getActivityRenderData(ts));

        p.setPageSize(page.getPageSize());

        p.setItems(datas);
        return p;
    }

    private List<Map> getActivityRenderData(List<TActivity> ts) {
        List<Map> datas = new ArrayList<Map>();

        //哨兵
        for(TActivity art:ts){
            Map temp = new HashMap();
            Map dataItem = new HashedMap();

            temp.put("origin_img_url", art.getCoverUrl());
            temp.put("img_url", art.getCoverUrl());
            temp.put("name",art.getTitle());
            temp.put("link",art.getId().toString());
            temp.put("dataId",art.getId().toString());
            temp.put("author",art.getAuthor());
            Date publishTime = DateUtil.getSysDate();
            if(StringUtil.isNotBlank(art.getPublishTime())){
                publishTime = DateUtil.getDate(art.getPublishTime(),"yyyy-MM-dd HH:mm:ss");
            }
            temp.put("publishTime", publishTime==null?DateUtil.getSysDate().getTime():publishTime.getTime());


            dataItem.put("item",temp);
            datas.add(dataItem);
        }

        return datas;
    }

    private List<Map> getInfoRenderData(List<TInformation> ts) {
        List<Map> datas = new ArrayList<Map>();

        //哨兵
//        int index = 0;
        for(TInformation art:ts){
            Map temp = new HashMap();
            Map dataItem = new HashedMap();
            String imgUrl = art.getCoverUrl();
            String[] imgUrls = imgUrl.split(ApiConstants.IMG_SPLIT);
//            if(index==0){
//
//                temp.put("img_url", imgUrls[0]);
//            }else{
            //兼容，后期需更迭
            if(ifAliyunImg(art)){
                temp.put("img_url", genAppImg(imgUrls,art.getFloorType(),art.getImgStatus().toString()));
            }else{
                temp.put("img_url", genAppImg(imgUrls,art));
            }
//            }
            temp.put("origin_img_url", art.getCoverUrl());
            temp.put("name",art.getTitle());
            temp.put("link",art.getId().toString());
            temp.put("dataId",art.getId().toString());
            temp.put("author",art.getAuthor());
            Date publishTime = DateUtil.getDate(art.getPublishTime(),"yyyy-MM-dd HH:mm:ss");
            temp.put("publishTime", publishTime==null?DateUtil.getSysDate().getTime():publishTime.getTime());
//            temp.put("ocTime", publishTime==null? Math.round(DateUtil.getSysDate().getTime()/1000): Math.round(publishTime.getTime()/1000));
            //图文专区有两种
            if(art.getFloorType().equals(TypeConstants.floorMap.get(IMAGE_FLOOR))){
                dataItem.put("code",art.getImgStatus().toString());
            }else{
                dataItem.put("code",art.getFloorType());
            }

            dataItem.put("item",temp);
            datas.add(dataItem);
//            index++;
        }


        return datas;
    }

    private boolean ifAliyunImg(TInformation art){
        return StringUtil.isBlank(art.getCoverUrl1()) ||
                (Integer.parseInt(TypeConstants.floorMap.get(IMAGE_BIG_FLOOR))==art.getImgStatus());
    }


    private List<String> genAppImg(String[] imgUrls,String code,String imgStatus){

        List<String> urls = new ArrayList<>();
        String splitFlag = "?";
        String nameSplitFlag = ".com";
        if(!CollectionUtils.isEmpty(Arrays.asList(imgUrls))){
            try {
                if(TypeConstants.floorMap.get(TypeConstants.SLIDER_FLOOR).equals(code)){
                    urls = genAppImgUrl(imgUrls, splitFlag, nameSplitFlag,slider_style);
                }else if(TypeConstants.floorMap.get(TypeConstants.TOP_FLOOR).equals(code)){
                    urls = genAppImgUrl(imgUrls, splitFlag, nameSplitFlag,video_style);
                }else if(TypeConstants.floorMap.get(IMAGE_FLOOR).equals(code)
                        && TypeConstants.floorMap.get(IMAGE_BIG_FLOOR).equals(imgStatus)){
                    urls = genAppImgUrl(imgUrls, splitFlag, nameSplitFlag,slider_style);
                }else if(TypeConstants.floorMap.get(IMAGE_FLOOR).equals(code)
                        && TypeConstants.floorMap.get(IMAGE_FLOOR).equals(imgStatus)){
                    urls = genAppImgUrl(imgUrls, splitFlag, nameSplitFlag,img_style);
                }else if(TypeConstants.floorMap.get(IMAGE_FLOOR).equals(code)
                        && TypeConstants.floorMap.get(TypeConstants.IMAGE_LR_FLOOR).equals(imgStatus)){
                    urls = genAppImgUrl(imgUrls, splitFlag, nameSplitFlag,video_style);
                }else if(TypeConstants.floorMap.get(TypeConstants.VIDEO_FLOOR).equals(code)){
                    urls = genAppImgUrl(imgUrls, splitFlag, nameSplitFlag,video_style);
                }else{
                    urls = genAppImgUrl(imgUrls, splitFlag, nameSplitFlag,img_style);
                }
            }catch (Exception e){
                logger.error(e.getMessage());
            }
        }

        return urls;
    }

    public List<String> genAppImgUrl(String[] imgUrls, String splitFlag, String nameSplitFlag,String style)
            throws Exception{
        List<String> urls = new ArrayList<>();
        for (String url : imgUrls){

            if(StringUtil.isBlank(url)) {
                urls.add("");
            }else{
                //在传参需要处理特殊字符

                urls.add(getAliyunUrlString(url,style,splitFlag,nameSplitFlag));
            }

        }
        return urls;
    }

    private String getAliyunUrlString(String url, String style,String splitFlag, String nameSplitFlag){
        String[] nameArr;
        String imgName = "";
        try{
            nameArr = URLDecoder.decode(url,"utf-8").split(nameSplitFlag);
            imgName =  nameArr[1].substring(1, nameArr[1].indexOf(splitFlag));
        }catch (Exception e){
            logger.error(e.getMessage());
        }
        return OssUpload.getImgStyleUrl(style,imgName);
    }

    private List<String> genAppImg(String[] imgUrls, TInformation art){

        List<String> urls = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(Arrays.asList(imgUrls))){
            if(imgUrls.length == 1){
                urls.add(art.getCoverUrl1());
            }else if(imgUrls.length == 2){
                urls.add(art.getCoverUrl1());
                urls.add(art.getCoverUrl2());

            }else if(imgUrls.length == 3){
                urls.add(art.getCoverUrl1());
                urls.add(art.getCoverUrl2());
                urls.add(art.getCoverUrl3());

            }
        }

        return urls;
    }



}
